<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ajax ajax_post请求</title>
    <script src="../../static/js/common.js"></script>
    <script src="../../static/js/jquery-3.6.3-min.js"></script>
</head>

<body>
    {% csrf_token %}
    <p>姓名: <input type="text" name="uname" id="uname"></p>
    <p>密码: <input type="password" name="password" id="password"></p>
    <p><input type="button" id="btn" value="确定提交"></p>


    <script>
        $(function () {
            $('#btn').click(function () {
                var xhr = createXhr();
                xhr.open('post', '/user/make_post/', true);
                var name = $('#uname').val();
                var pwd = $('#password').val();
                // 拿到csrf_token的name
                var csrf_name = $("[name='csrfmiddlewaretoken']").val(); // jq属性选择器

                // ajax post提交需要设置请求头. 他的默认值Content-Type为, 'text/plain;charset=utf8'
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                xhr.onreadystatechange = function () {
                    if (xhr.readyState == 4 && xhr.status == 200) {
                        alert(xhr.responseText);
                    }
                }

                // 拼接Ajax的post表单提交的参数
                var parmas = 'uname=' + name + '&pwd=' + pwd + '&csrfmiddlewaretoken=' + csrf_name
                xhr.send(parmas)
            });


        });
    </script>
</body>

</html>